{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "078c16c7-e88e-4e0e-b72e-d23f34a26cd2",
   "metadata": {},
   "outputs": [],
   "source": [
    "import struct\n",
    "import hmac\n",
    "import hashlib\n",
    "\n",
    "with open('./tls_key.bin', 'rb') as fp:\n",
    "    tls_key = fp.read()\n",
    "\n",
    "magic, key_offset, key_len, aad_offset, aad_len, hmac_offset, hmac_len = struct.unpack('<IIIIIII', tls_key[:28])\n",
    "key = tls_key[key_offset: key_offset + key_len]\n",
    "aad = tls_key[aad_offset: aad_offset + aad_len]\n",
    "sig = tls_key[hmac_offset: hmac_offset + hmac_len]\n",
    "\n",
    "hmac_key = hashlib.sha256(b'FPC_HMAC_KEY\\0').digest()\n",
    "h = hmac.new(hmac_key, digestmod='SHA-256')\n",
    "h.update(aad)\n",
    "h.update(key)\n",
    "assert(h.digest() == sig)\n",
    "\n",
    "key, aad, sig"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0c3b7d47-2ab7-4353-8fc0-5221c716aa2d",
   "metadata": {},
   "outputs": [],
   "source": [
    "from Crypto.Cipher import AES"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c3f6f63d-907f-459b-95f7-6a431bfffb0b",
   "metadata": {},
   "outputs": [],
   "source": [
    "fpc_sealing_key = b'FPC_SEALING_KEY\\0'\n",
    "\n",
    "aes = AES.new(hashlib.sha256(fpc_sealing_key).digest(), AES.MODE_CBC, iv=b'\\0'*16)\n",
    "k = aes.decrypt(key)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f15361d5-fd2d-4a7f-8c0e-e5c37dc37282",
   "metadata": {},
   "outputs": [],
   "source": [
    "len(k)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2e67a070-3919-4da5-8eac-12816b903cd2",
   "metadata": {},
   "outputs": [],
   "source": [
    "k.hex()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d1e78688-a9ba-43bb-a7f7-5747e7d17563",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
